package chapter14.Collection.Set.Exercise;

import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @Auther: Tx
 * @Date: 2022/5/12 23:17
 */
@SuppressWarnings("all")
public class LinkedHashSetExercise {
    public static void main(String[] args) {
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        linkedHashSet.add(new Car("宝马",555));
        linkedHashSet.add(new Car("宝马",555));
        System.out.println(linkedHashSet);


    }
}

class Car {
    private String name;
    private double price;

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }
//调用hashcode后，还会进一步调用equals方法，比较两个对象的值是否相同。
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return this.name.equals(car.name)&& this.price == car.price;
    }
//通过相同的值产生相同的hash值，因为底层会调用来比较是否是一个对象。
    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}